#!/bin/sh

# Source: https://github.com/azlux/log2ram
# License: MIT
# License file: /usr/share/log2ram/LICENSE

SIZE=40M
USE_RSYNC=false
ENABLED=false

[ -f /etc/default/log2ram ] && . /etc/default/log2ram

[ "$ENABLED" != true ] && exit 0

# don't touch anything below here.

HDD_LOG=/var/log.hdd/
RAM_LOG=/var/log/
LOG2RAM_LOG="${HDD_LOG}log2ram.log"
LOG_OUTPUT="tee -a $LOG2RAM_LOG"

isSafe () {
    [ -d $HDD_LOG ] || echo "ERROR: $HDD_LOG doesn't exist!  Can't sync."
    [ -d $HDD_LOG ] || exit 1
}

syncToDisk () {
    isSafe

    if [ "$USE_RSYNC" = true ]; then
        rsync -aXWv --delete --exclude log2ram.log --links $RAM_LOG $HDD_LOG 2>&1 | $LOG_OUTPUT
    else
        cp -rfup $RAM_LOG -T $HDD_LOG 2>&1 | $LOG_OUTPUT
    fi
}

syncFromDisk () {
    isSafe

    if [ "$USE_RSYNC" = true ]; then
        rsync -aXWv --delete --exclude log2ram.log --links $HDD_LOG $RAM_LOG 2>&1 | $LOG_OUTPUT
    else
        cp -rfup $HDD_LOG -T $RAM_LOG 2>&1 | $LOG_OUTPUT
    fi
}


case "$1" in
  start)
      [ -d $HDD_LOG ] || mkdir $HDD_LOG
      rm -f $LOG2RAM_LOG
      mount --bind $RAM_LOG $HDD_LOG
      mount --make-private $HDD_LOG
      mount -t tmpfs -o nosuid,noexec,nodev,mode=0755,size=$SIZE log2ram $RAM_LOG
      syncFromDisk
      ;;

  stop)
      syncToDisk
      umount -l $RAM_LOG
      umount -l $HDD_LOG
      ;;

  write)
      syncToDisk
      ;;
  *)
      echo "Usage: log2ram {start|stop|write}" >&2
      exit 1
      ;;
esac
